<script setup lang="ts">
import { ref } from "vue";
import { reqAtttAPI } from "@/apis/product/attr";
import { reqSpuImageListAPI, reqSpuSaleAttrListAPI, reqAddSkuAPI } from "@/apis/product/spu";
import type { SkuData } from "@/apis/product/spu/type";
import { ElMessage } from "element-plus";
//父组件向子组件传参 自定义事件
let $emit = defineEmits(["changeShow"]);
//点击页面取消按钮
const cancel = () => {
    $emit("changeShow", 0);
};
//储存接口数据
//平台属性
let attrArr = ref<any>([])
//销售属性
let saleAttr = ref<any>([])
//照片墙
let imgArr = ref<any>([])
//table表格实例
let imgTable = ref<any>()
//收集页面用户的数据
let skuParams = ref<SkuData>({
    //父组件会传过来前三个参数
    category3Id: '', //三级分类的ID
    spuId: '', //已有的SPU的ID
    tmId: '',//SPU品牌的ID
    //v-model 收集页面用户数据
    skuName: '',//sku名字
    price: '',//sku价格
    weight: '', //sku重量
    skuDesc: '',  //sku的描述
    skuAttrValueList: [],
    skuSaleAttrValueList: [],
    skuDefaultImg: '',//sku图片地址
})
//当前子组件的方法 对外暴露
const initSkuData = async (c1Id: number | string, c2Id: number | string, spu: any) => {
    skuParams.value.category3Id = spu.category3Id
    skuParams.value.spuId = spu.id
    skuParams.value.tmId = spu.tmId
    //获取平台属性
    let result = await reqAtttAPI(c1Id, c2Id, spu.category3Id);
    //获取获取图片列表
    let result1 = await reqSpuImageListAPI(spu.id)
    //获取销售属性
    let result2 = await reqSpuSaleAttrListAPI(spu.id)
    attrArr.value = result.data
    imgArr.value = result1.data
    saleAttr.value = result2.data
}
defineExpose({
    initSkuData
});
//点击页面设置默认按钮
const handler = (row: any) => {
    skuParams.value.skuDefaultImg = row.imgUrl
    //清空选择
    imgArr.value.forEach((item: any) => {
        imgTable.value.toggleRowSelection(item, false)
    })
    //选中
    imgTable.value.toggleRowSelection(row, true)
}
//保存按钮
const save = async () => {
    // 平台属性处理（安全版本）
    skuParams.value.skuAttrValueList = attrArr.value .filter((item:any)=> item?.attrIdAndValueId) // 过滤掉undefined/null
        .map((item:any) => {
            const parts = item.attrIdAndValueId.split(':');
            if (parts.length !== 2) {
                return null;
            }
            return {
                attrId: parts[0].trim(),
                valueId: parts[1].trim()
            };
        })
        .filter(Boolean); // 过滤掉无效项

    // 销售属性处理（安全版本）  
    skuParams.value.skuSaleAttrValueList = saleAttr.value
        .filter((item:any) => item?.saleIdAndValueId) // 过滤掉undefined/null
        .map((item:any) => {
            const parts = item.saleIdAndValueId.split(':');
            if (parts.length !== 2) {
                return null;
            }
            return {
                saleAttrId: parts[0].trim(),
                saleAttrValueId: parts[1].trim()
            };
        })
        .filter(Boolean); // 过滤掉无效项
    //发请求
    let result: any = await reqAddSkuAPI(skuParams.value)
    if (result.code === 200) {
        ElMessage.success('添加成功')
        cancel()
    } else {
        ElMessage.error('添加失败')
    }
}

</script>
<template>
    <el-form>
        <el-form-item label="sku名称" label-width="100px">
            <el-input placeholder="请输入内容" v-model="skuParams.skuName"></el-input>
        </el-form-item>
        <el-form-item label="sku价格(元)" label-width="100px">
            <el-input type="number" placeholder="请输入价格" v-model="skuParams.price"></el-input>
        </el-form-item>
        <el-form-item label="sku重量(克)" label-width="100px">
            <el-input type="number" placeholder="请输入重量" v-model="skuParams.weight"></el-input>
        </el-form-item>
        <el-form-item label="sku描述" label-width="100px">
            <el-input type="textarea" placeholder="请输入内容" v-model="skuParams.skuDesc"></el-input>
        </el-form-item>
        <el-form-item label="平台属性" label-width="100px">
            <el-form inline>
                <el-form-item v-for="item in attrArr" :key="item.id" :label="item.attrName">
                    <el-select placeholder="请选择" v-model="item.attrIdAndValueId">
                        <el-option :value="`${item.id}:${attrValue.id}`" v-for="attrValue in item.attrValueList"
                            :key="attrValue.id" :label="attrValue.valueName"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
        </el-form-item>
        <el-form-item label="销售属性" label-width="100px">
            <el-form>
                <el-form-item v-for="item in saleAttr" :key="item.id" :label="item.saleAttrName">
                    <el-select placeholder="请选择" v-model="item.saleIdAndValueId">
                        <el-option :value="`${item.id}:${saleAttrValue.id}`" v-for="saleAttrValue in
                            item.spuSaleAttrValueList" :key="saleAttrValue.id"
                            :label="saleAttrValue.saleAttrValueName"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
        </el-form-item>
        <el-form-item label=" 图片名称" label-width="100px">
            <el-table border :data="imgArr" ref="imgTable">
                <el-table-column type="selection" width="80px" align="center"> </el-table-column>
                <el-table-column label="图片">
                    <template #="{ row }">
                        <img :src="row.imgUrl" alt="" style="height: 100px;  width: 100px;"></img>
                    </template>
                </el-table-column>
                <el-table-column label="名称" prop="imgName"> </el-table-column>
                <el-table-column label="操作">
                    <template #="{ row }">
                        <el-button type="danger" @click="handler(row)">设置默认</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>
        <el-form-item label-width="100px">
            <el-button type="primary" @click="save">保存</el-button>
            <el-button @click="cancel">取消</el-button>
        </el-form-item>
    </el-form>
</template>
<style scoped></style>